package cn.devices.controller;


import cn.devices.dto.UserAuthDto;
import cn.devices.entity.TbAuthDm;
import cn.devices.entity.TbAuthUser;
import cn.devices.model.JsonMessage;
import cn.devices.service.TbAuthUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 设备个人授权表 前端控制器
 * </p>
 *
 * @author 秋水浮萍
 * @since 2021-02-07
 */
@RestController
@RequestMapping("/tb-auth-user")
public class TbAuthUserController {

    @Autowired
    private TbAuthUserService tbAuthUserService;

    /**
     * 添加个人授权信息
     *
     * @param tbAuthUser
     * @return
     */
    @PostMapping("tbAuthUserAdd")
    public JsonMessage tbAuthUserAdd(@RequestBody TbAuthUser tbAuthUser) {
        JsonMessage message = new JsonMessage();
        try {
            tbAuthUser.setAuthorizeTime(new Date());
            tbAuthUserService.tbAuthUserAdd(tbAuthUser);
            message.setData("授权成功");
        } catch (DuplicateKeyException e) {
            message.setData("已存在");
        }
        return message;
    }

    /**
     * 删除个人授权
     *
     * @param deviceCode
     * @param userId
     * @return
     */
    @GetMapping("tbAuthUserDelete")
    public JsonMessage tbAuthUserDelete(String deviceCode, String userId) {
        JsonMessage message = new JsonMessage();
        tbAuthUserService.tbAuthUserDelete(deviceCode, userId);
        message.setData("删除成功");
        return message;
    }

    /**
     * 个人权限列表
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("tbAuthUserPageInfo")
    public JsonMessage tbAuthUserPageInfo(@RequestParam(defaultValue = "1") int pageIndex,
                                          @RequestParam(defaultValue = "10") int pageSize) {
        JsonMessage message = new JsonMessage();
        PageInfo<UserAuthDto> pageInfo = tbAuthUserService.updateUserList(pageIndex, pageSize);
        message.setData(pageInfo);
        return message;
    }


    /**
     * 根据用户id查询所有授权的类型
     *
     * @param userId
     * @return
     */
    @GetMapping("tbAuthUserById")
    public JsonMessage tbAuthUserById(String userId) {
        JsonMessage message = new JsonMessage();
        List<TbAuthUser> tbAuthDmList = tbAuthUserService.userAuthUserById(userId);
        message.setData(tbAuthDmList);
        return message;
    }
}
